from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
from keras.applications.vgg16 import decode_predictions
from keras.models import Model
from numpy import linalg as LA
import numpy as np
from keras import backend as k
from skimage.measure import block_reduce

# conf = k.tf.ConfigProto(device_count={'CPU': 2},
#                         intra_op_parallelism_threads=2,
#                         inter_op_parallelism_threads=2)
# k.set_session(k.tf.Session(config=conf))

def ext_pre(img_path):
    # k.clear_session()
    model = VGG16()
    model_2 = Model(inputs=model.input, outputs=model.get_layer('block5_pool').output)
    img = load_img(img_path, target_size=(224, 224))
    im = img_to_array(img)
    im = np.expand_dims(im, axis=0)
    im = preprocess_input(im)


    features = model_2.predict(im)
    features_2 = block_reduce(features, block_size=(1, 7, 7, 1), func=np.max)  # maxpooling
    features_3 = features_2.flatten().reshape(1, 512)  # reshape data
    norm_feat = features_3[0] / LA.norm(features_3[0])
    feat = model.predict(im).round(6)
    labels_org = decode_predictions(feat, top=10)
    labels = [i[1] for i in labels_org[0]]
    percent = [i[2] for i in labels_org[0]]
    # k.clear_session()
    return labels, percent, norm_feat
    # labels 标签，10个，列表
    # percent 对应的标签概率，10个, 列表
    # norm_feat 特征，512维数组，数组，float32


if __name__ == '__main__':
    import time
    for i in range(30):
        img_path = 'C:/Users/Administrator/Desktop/搜索结果/微信图片_20190307160122.png'
        start = time.time()
        print('----------------------------------------***-------------------------------------------')
        print(ext_pre(img_path))
        end = time.time()
        print('单次耗时', end-start)
